package com.exampl.springstack.common.utils;

import org.springframework.scheduling.annotation.Scheduled;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Qiangfanghao
 * 本地缓存
 */
public class LocalCacheUtils {

    /**缓存默认失效时间(毫秒)*/
    private static final long DEFAULT_TIMEOUT = 60 * 60 * 1000;

    /** 缓存清除动作执行间隔  1 分钟执行一次 */
    private static final String CRON = "0 0/1 * * * ?";

    /**缓存存储的map*/
    private static final ConcurrentHashMap<String,CacheEntity> cacheMap = new ConcurrentHashMap<>();


    public LocalCacheUtils() {
    }

    private static LocalCacheUtils cache = null;


    /**
     * 定时清理
     */
    @Scheduled(cron = CRON)
    public void scheduledClean() {
        for (String key:cacheMap.keySet()) {
            CacheEntity entity = cacheMap.get(key);
            long now = System.currentTimeMillis();
            if ((now - entity.getTimeStamp()) >= entity.getExpire()) {
                cacheMap.remove(key);
            }
        }
    }




    /**存储单元*/
    static class CacheEntity {

        /**值*/
        private Object value;

        /**过期时间(毫秒)*/
        private long expire;

        /**创建时的时间戳*/
        private long timeStamp;

        public Object getValue() {
            return value;
        }

        public void setValue(Object value) {
            this.value = value;
        }

        public long getExpire() {
            return expire;
        }

        public void setExpire(long expire) {
            this.expire = expire;
        }

        public long getTimeStamp() {
            return timeStamp;
        }

        public void setTimeStamp(long timeStamp) {
            this.timeStamp = timeStamp;
        }
    }

    public static boolean push(String key,Object value,long expire) {
        //清理 相同key的本地数据
        remove(key);
        cacheMap.put(key,setEntity(key,value,expire));

        return true;
    }


    public static boolean push(String key,Object value) {
        //清理 相同key的本地数据
        remove(key);
        cacheMap.put(key,setEntity(key,value,DEFAULT_TIMEOUT));

        return true;
    }

    /**
     *
     * @param key
     * @param value
     * @param expire (毫秒)
     * @return
     */
    private static CacheEntity setEntity(String key,Object value,long expire){

        CacheEntity entity = new CacheEntity();
        entity.setValue(value);
        entity.setExpire(expire);
        entity.setTimeStamp(System.currentTimeMillis());

        return entity;
    }

    public static Object get(String key) {
        CacheEntity entity = cacheMap.get(key);

        if (entity == null) {
            return null;
        } else {
            Object value = entity.getValue();
            if (value == null) {
                return null;
            }
            return value;
        }
    }

    public static void remove(String key) {
        cacheMap.remove(key);
    }

}
